<?php
/**
 * Created by PhpStorm.
 * User: lih
 * Date: 2018/4/22
 * Time: 20:09
 */

namespace frontend\api\action;

use Yii;
use yii\db\Query;
use common\models\User;

class Getpostlist extends BaseAction
{
    const POST_PAGE_SIZE = 20;

    /**
     * @param $arrayData array
     * @param $returnData array
     * @throws \Exception
     */
    public function runAction($arrayData, &$returnData)
    {
        $paramFid = $this->trimNullParam(@$arrayData['fid']);
        $paramP = $this->trimNullParam(@$arrayData['p']);

        $tableNameThread = $this->getDzTableName('forum_thread');

        $pageQuery = (new Query())->from($tableNameThread)
            ->where("`fid`=:fid AND `displayorder`>='0'", [
                ":fid" => $paramFid,
            ])
            ->orderBy( '`displayorder` DESC, `dateline` DESC');
        $pageDataQuery = $this->queryPageData($pageQuery, $paramP, Getpostlist::POST_PAGE_SIZE);
        if(!empty($pageDataQuery)) {
            $dataQuery = $pageDataQuery['data'];

            $nodeList = array();
            if(!empty($dataQuery)) {
                foreach ($dataQuery as $dataItem) {
                    $nodeList[] = $this->convertDataQueryToPost($dataItem);
                }
            }

            $returnData['code'] = '0';
            $returnData['msg'] = '';
            $returnData['list'] = $nodeList;
            if(!empty($pageDataQuery['p'])) {
                $returnData['p'] = $pageDataQuery['p'];
            }
        } else {
            $returnData['code'] = '0';
            $returnData['msg'] = '';
            $returnData['list'] = array();
        }
    }

    private function convertDataQueryToPost($dataItem)
    {
        $objItem = array();
        $objItem['pid'] = $this->trimNullParam(@$dataItem['tid']);
        $objItem['subject'] = $this->trimNullParam(@$dataItem['subject']);
        $strMediaextra = $this->trimNullParam(@$dataItem['mediaextra']);
        if(!empty($strMediaextra)) {
            $objItem['mediaextra'] = json_decode($strMediaextra, true);
        }
        $objItem['views'] = $this->trimNullParam(@$dataItem['views']);
        $objItem['replies'] = $this->trimNullParam(@$dataItem['replies']);
        $objItem['createtime'] = $this->trimNullParam(@$dataItem['dateline']);
        $objItem['updatetime'] = $this->trimNullParam(@$dataItem['lastpost']);
        return $objItem;
    }

}
